package lv.accenture.ex06;

import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.List;

public class ProcessingMain {
	public static String filename;
	public static void main(String[] args) throws IOException {
		filename = args[0];
		IResourceList rList = new FSResourceList("src/main/resources/retiman");
		String[] resources = rList.getAllResources();
		System.out.println("total # of tags is " + resources.length);

		RegexExtractor extractor = new RegexExtractor();
		
		  FileOutputStream fis = new FileOutputStream(filename);
		  OutputStreamWriter osw = new OutputStreamWriter(fis, "UTF-8");
		  BufferedWriter bw = new BufferedWriter(osw);
		  bw.flush();
		  bw.close();
		  osw.close();
		  fis.close();
		  
		for (int i = 0; i < resources.length; i++) {
			List<Bookmark> bookmarks = extractor.extractBookmarks(resources[i]);
			writeJSON(filename,bookmarks);
		}
		
	}
	public static void writeJSON(String fileName, List<Bookmark> bookmarks) throws IOException {
		  FileOutputStream fis = new FileOutputStream(fileName, true);
		  OutputStreamWriter osw = new OutputStreamWriter(fis, "UTF-8");
		  BufferedWriter bw = new BufferedWriter(osw);
		  bw.append("{\"items\" : [\n"); // write preamble of JSON file
		  for (Bookmark b: bookmarks) {			  
		    bw.append("\t"+b.toString()+",\n"); // output each bookmark
		  }
		  bw.append("]}\n"); // write closing part of JSON
		  bw.close();
		  osw.close();
		  fis.close();
	}
}
